<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        position: absolute;
        left: 0px;
        width: 200px;
        height: 200px;
        background-color: blue;
      }
      span {
        position: absolute;
        top: 50%;
        display: block;
        width: 100px;
        height: 100px;
        background-color: purple;
      }
    </style>
  </head>
  <body>
    <button>点击</button>
    <span></span>
    <div></div>

    <script>
      var btn = document.querySelector("button");
      var div = document.querySelector("div");
      var span = document.querySelector("span");
      function animate(obj, target) {
        //给不同的元素添加了不同的定时器
        //无论点击多少次，都只有一个定时器运行
        clearInterval(obj.timer);
        obj.timer = setInterval(function () {
          if (obj.offsetLeft >= target) {
            clearInterval(obj.timer);
          } else {
            obj.style.left = obj.offsetLeft + 1 + "px";
          }
        }, 10);
      }
      btn.addEventListener("click", function () {
        animate(div, 400);
        animate(span, 400);
      });
    </script>
  </body>
</html>
